#include <hd_oled.h>
#include <pd_gpio.h>
#include <pd_i2c_hd.h>
#include <hd_oled_protocol_i2c.h>
#include <delay.h>
#include <pd_exti.h>
#include "main.h"


#define ARRAY_SIZE(x)       sizeof(x) / sizeof(x[0])
#define USE_HARDWARE_SPI    1
#define USE_HARDWARE_I2C    1
OLED oled;

uint8_t count = 0;

extern void SystemClock_Config(void);

void oled_instance(OLED *oled);

int main(void) {

    SystemClock_Config();

    NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_2);

    oled_instance(&oled);

    OLED_printf(&oled, 0, 0, "Stop 0 Mode");
    OLED_printf(&oled, 0, 16, "Count:");
    OLED_refresh(&oled);

    // EXTI to Wakeup
    GPIO extiGPIO;
    GPIO_constructor(&extiGPIO, GPIOA, LL_GPIO_PIN_0);

    ExtIR externalTI;
    ExtIR_constructor(&externalTI, &extiGPIO, LL_EXTI_LINE_0, LL_SYSCFG_EXTI_PORTA, LL_SYSCFG_EXTI_LINE0);
    ExtIR_init(&externalTI, EXTI0_IRQn, 2, 2);

    while (1) {
        OLED_printf(&oled, 0, 32, "Running");
        OLED_refresh(&oled);
        delay_ms(1000);
        OLED_printf(&oled, 0, 32, "       ");
        OLED_refresh(&oled);
        delay_ms(1000);


        // SCB_SCR_SLEEPDEEP
        LL_LPM_EnableDeepSleep();

#define LPR 1

#ifdef MR
        // Stop 0 for Main Regulator: PWR_CR_PDDS = 0, PWR_CR_LPDS = 0
        LL_PWR_SetPowerMode(LL_PWR_MODE_STOP_MAINREGU);
#elif LPR
        // Stop 1 for Low-power Regulator: PWR_CR_PDDS = 0, PWR_CR_LPDS = 1
        LL_PWR_SetPowerMode(LL_PWR_MODE_STOP_LPREGU);
#endif
        __WFI();

        // Wakeup by any EXTI line, and then run from this
        SystemClock_Config();
    }
}

void EXTI0_IRQHandler(void) {
    if (LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_0) != RESET) {
        LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_0);

        count++;

        OLED_printf(&oled, 56, 16, "%03d", count);
        OLED_refresh(&oled);
    }
}


void oled_instance(OLED *oled) {
    // I2C gpio init
    static GPIO oledSckGPIO, oledSdaGPIO;
    GPIO_constructor(&oledSckGPIO, GPIOB, LL_GPIO_PIN_10); // I2Cx_SCK
    GPIO_constructor(&oledSdaGPIO, GPIOB, LL_GPIO_PIN_11); // I2Cx_SDA

#ifdef USE_HARDWARE_I2C
    static I2CHardware i2c2;
    I2CHardware_constructor(&i2c2, I2C2, &oledSckGPIO, &oledSdaGPIO);
#elif USE_SIMULATE_I2C
    static I2CSimulate i2c2;
    I2CSimulate_constructor(&i2c2, &oledSckGPIO, &oledSdaGPIO);
#endif
    I2C_init((I2C *) &i2c2);

    // OLED protocol of I2C
    static OLEDProtocolI2C oledProtocolI2c;
    OLEDProtocolI2C_constructor(&oledProtocolI2c, (I2C *) &i2c2);

    // OLED font instance.
    static OLEDFont oledFont;
    OLEDFont_contructor(&oledFont, NULL);

    // OLED instance of 4-PIN(I2C)
    OLED_constructor(oled, (OLEDProtocol *) &oledProtocolI2c, &oledFont);

    OLED_init(oled);

    OLED_clear(oled);
    OLED_refresh(oled);
}

